<?php

namespace app\admin\controller\vppz;

use app\common\controller\Backend;
//use think\addons\Service;
//use think\Exception;

use app\admin\model\vppz\App;


/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class Config extends Base
{
	protected $branch = 0;	// 0：插件市场版，1：自主授权版

    protected $model = null;
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

		$this->view->assign("VP_BRANCH", $this->branch);
    }

    /**
     * 编辑
     */
    public function index()
    {
		$AppModel = new App;
		$app = $AppModel->find($this->app_id);

		// 首次进入，默认创建App
		if(empty($app)){
			$AppModel->save(['id'=>$this->app_id,'name'=>'嘀嗒陪护']);
			$app = $AppModel->find($this->app_id);
		}
        if(empty($app['family_benefits']) === FALSE){
            $app['family_benefits'] = json_decode($app['family_benefits'],true);
        }
		$this->view->assign("datas", ['config' => $app]);

		return $this->view->fetch();
    }

	// 保存
	public function edit($ids = NULL){
		$AppModel = new App;
		$app = $AppModel->find($this->app_id);

		if ($this->request->isPost()) {
			$params = $this->request->post("row/a", [], 'trim');

			if($this->branch==1){
				if(empty($params['vpkey'])){
					$this->error('请填写授权KEY');
				}
				$vpkey = \addons\vppz\library\Vpower::pdecode($params['vpkey']);
				if(empty($vpkey) || $vpkey!=$params['wxapp_id']){
					$this->error('授权KEY无效');
				}
			}

            if ($params) {
				// 应用配置空，新增；不空，更新
                if(empty($params['family_benefits']) === FALSE){
                    $params['family_benefits'] = json_encode($params['family_benefits']);
                }
				if(empty($app)){
					$AppModel->save($params);
				}else{
					$AppModel->save($params,['id' => $app['id']]);
				}

                 $this->success();

            }else{
				$this->error(__('Parameter %s can not be empty', ''));
			}
		}

	}


	// 插件配置
	public function plugin(){
		$name = $this->request->get('name');

        if ($name == 'oss') {
            $config = config('addons.hooks');
            if (isset($config['upload_config_init']) && $config['upload_config_init']) {
                $availableArr = array_intersect($config['upload_config_init'], ['alioss', 'bos', 'cos', 'upyun', 'ucloud', 'hwobs', 'qiniu']);
                if ($availableArr) {
                    $name = reset($availableArr);
                }
            }
            if (!$name || $name == 'oss') {
                $this->error("请在插件管理中安装一款云存储插件", "");
            }
        } else {
            $info = get_addon_info($name);
            $addonArr = [
                'epay'   => '微信支付宝整合'
            ];
            if (!$info) {
                $this->error('请检查对应插件' . (isset($addonArr[$name]) ? "《{$addonArr[$name]}》" : "") . '是否安装且启动', "");
            }
        }
        $this->redirect('addon/config?name=' . $name . '&dialog=1');
	}

}
